package it.cums.util;

import it.cums.base.Activator;
import it.cums.model.Country;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class CountryManager {
	private static CountryManager countryManager;
	
	private CountryManager() {
	}
	
	public static CountryManager getInstance() {
		if (countryManager == null) {
			countryManager = new CountryManager();
		}
		return countryManager;
	}
	
	@SuppressWarnings("unchecked")
	public List<Country> listCountries() {
		Session session = null;
		Transaction tx = null;
		List<Country> countries = new ArrayList<Country>();
		try {
			session = HibernateUtil.getSessionFactory().openSession();
		    tx = session.beginTransaction();
		    countries = session.createQuery("from Country as c order by c.description").list();
		    tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			HibernateUtil.rollback(tx);
		} finally {
			HibernateUtil.closeSession(session);
		}
		return countries;
    }
	
	public void initializeCountries() {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			tx = session.beginTransaction();
			File file = Activator.getFile("./sql/import.sql");
			FileReader f = new FileReader(file);
			BufferedReader br = new BufferedReader(f);
			String line = br.readLine();
			while (line != null) {
				session.createSQLQuery(line).executeUpdate();
				line = br.readLine();
			}
			f.close();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			HibernateUtil.rollback(tx);
		} finally {
			HibernateUtil.closeSession(session);
		}
	}
}
